<template>
	<view class="container">
		<view class="header">
			<view class="title">停车服务申请</view>
			<view class="subtitle">查看我的停车服务申请记录</view>
		</view>
		
		<!-- 申请列表 -->
		<view class="application-list" v-if="applications.length > 0">
			<view class="application-item" v-for="(application, index) in applications" :key="application.application_id">
				<view class="application-header">
					<view class="application-id">申请编号: {{ application.application_id }}</view>
					<view :class="['application-status', getStatusClass(application.status)]">{{ getStatusText(application.status) }}</view>
				</view>
				
				<view class="application-content">
					<view class="info-row">
						<text class="info-label">车牌号码:</text>
						<text class="info-value">{{ application.vehicle ? application.vehicle.plate_number : '未知' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">申请日期:</text>
						<text class="info-value">{{ formatDate(application.application_time) }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">期望开始日期:</text>
						<text class="info-value">{{ application.expected_start_date }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">租赁时长:</text>
						<text class="info-value">{{ application.expected_duration }}个月</text>
					</view>
				</view>
				
				<!-- 不同状态显示不同操作 -->
				<view class="application-actions">
					<!-- 初审通过状态显示填写合同按钮 -->
					<button 
						class="action-btn primary-btn" 
						v-if="application.status === 'initial_approved'"
						@click="fillContract(application)"
					>
						填写合同
					</button>
					
					<!-- 待审批状态显示取消按钮 -->
					<button 
						class="action-btn cancel-btn" 
						v-if="application.status === 'pending'"
						@click="cancelApplication(application)"
					>
						取消申请
					</button>
					
					<!-- 查看详情按钮 -->
					<button class="action-btn detail-btn" @click="viewDetail(application)">查看详情</button>
				</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view class="empty-state" v-else>
			<image class="empty-icon" src="/static/icons/empty.png" mode="aspectFit"></image>
			<text class="empty-text">暂无申请记录</text>
			<text class="empty-desc">点击下方按钮创建停车申请</text>
		</view>
		
		<!-- 底部操作 -->
		<view class="bottom-action">
			<button class="add-btn" @click="navigateToApply">
				<text class="btn-icon">+</text>
				<text>新增停车申请</text>
			</button>
		</view>
		
		<!-- 使用自定义合同弹窗组件 -->
		<contract-popup 
			:show="showContractPopup" 
			@close="closeContractPopup" 
			@submit="submitContract"
		></contract-popup>
	</view>
</template>

<script>
	import { getParkingApplications, cancelParkingApplication, submitParkingContract } from '@/api/parking.js'
	import ContractPopup from '@/components/contract-popup.vue'
	
	export default {
		components: {
			ContractPopup
		},
		data() {
			return {
				applications: [],
				isLoading: false,
				currentApplication: null,
				showContractPopup: false
			}
		},
		onShow() {
			// 每次页面显示时获取最新数据
			this.fetchApplications()
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.fetchApplications(() => {
				uni.stopPullDownRefresh()
			})
		},
		methods: {
			// 获取申请列表
			fetchApplications(callback) {
				// 检查登录状态
				const token = uni.getStorageSync('token')
				if (!token) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}, 1500)
					return
				}
				
				this.isLoading = true
				console.log('开始获取停车申请列表...')
				
				// 调用API获取当前用户的申请列表
				getParkingApplications()
					.then(data => {
						console.log('获取停车申请列表成功:', data)
						// 正确处理嵌套的响应结构
						if (data && data.data && data.data.results) {
							this.applications = data.data.results
							// 调试每个申请的状态
							this.applications.forEach(app => {
								console.log(`申请ID: ${app.application_id}, 状态: ${app.status}, 状态文本: ${this.getStatusText(app.status)}`)
							})
						} else {
							this.applications = []
						}
						console.log('处理后的申请列表:', this.applications)
						console.log('申请列表长度:', this.applications.length)
					})
					.catch(err => {
						console.error('获取申请列表失败', err)
						uni.showToast({
							title: err.message || '获取申请列表失败',
							icon: 'none'
						})
					})
					.finally(() => {
						this.isLoading = false
						if (callback) callback()
					})
			},
			
			// 跳转到申请页面
			navigateToApply() {
				uni.navigateTo({
					url: '/pages/parking/apply'
				})
			},
			
			// 查看申请详情
			viewDetail(application) {
				uni.navigateTo({
					url: `/pages/parking/application-detail?id=${application.application_id}`
				})
			},
			
			// 取消申请
			cancelApplication(application) {
				uni.showModal({
					title: '取消确认',
					content: '确定要取消此停车申请吗？',
					confirmText: '确定取消',
					confirmColor: '#ff4d4f',
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '取消中...'
							})
							
							cancelParkingApplication(application.application_id)
								.then(() => {
									uni.hideLoading()
									uni.showToast({
										title: '申请已取消',
										icon: 'success'
									})
									// 重新获取列表
									this.fetchApplications()
								})
								.catch(err => {
									uni.hideLoading()
									console.error('取消申请失败', err)
									uni.showToast({
										title: err.message || '取消失败',
										icon: 'none'
									})
								})
						}
					}
				})
			},
			
			// 填写合同
			fillContract(application) {
				console.log('尝试填写合同，申请状态:', application.status)
				
				// 再次验证状态是否为初审通过
				if (application.status !== 'initial_approved') {
					uni.showToast({
						title: '只有初审通过的申请才能填写合同',
						icon: 'none'
					})
					return
				}
				
				this.currentApplication = application
				this.showContractPopup = true
			},
			
			// 关闭合同弹窗
			closeContractPopup() {
				console.log('关闭合同弹窗')
				this.showContractPopup = false
			},
			
			// 提交合同
			submitContract() {
				console.log('提交合同, 当前申请:', this.currentApplication)
				
				uni.showLoading({
					title: '提交中...'
				})
				
				// 调用API提交合同
				submitParkingContract(this.currentApplication.application_id, {
					contract_id: 1 // 默认合同ID为1
				})
					.then(() => {
						uni.hideLoading()
						this.closeContractPopup()
						uni.showToast({
							title: '合同提交成功',
							icon: 'success'
						})
						// 重新获取列表
						this.fetchApplications()
					})
					.catch(err => {
						uni.hideLoading()
						console.error('提交合同失败', err)
						uni.showToast({
							title: err.message || '提交失败',
							icon: 'none'
						})
					})
			},
			
			// 格式化日期
			formatDate(dateString) {
				if (!dateString) return '未知'
				const date = new Date(dateString)
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
			},
			
			// 获取状态文本
			getStatusText(status) {
				console.log('获取状态文本，原始状态:', status)
				const statusMap = {
					'pending': '待审批',
					'initial_approved': '初审通过',
					'rejected': '已拒绝',
					'contract_pending': '待审核',
					'approved': '已通过',
					'cancelled': '已取消'
				}
				const result = statusMap[status] || status
				console.log('状态文本结果:', result)
				return result
			},
			
			// 获取状态样式类
			getStatusClass(status) {
				const classMap = {
					'pending': 'status-pending',
					'initial_approved': 'status-initial-approved',
					'rejected': 'status-rejected',
					'contract_pending': 'status-contract-pending',
					'approved': 'status-approved',
					'cancelled': 'status-cancelled'
				}
				return classMap[status] || ''
			}
		}
	}
</script>

<style>
	.container {
		padding: 30rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	.header {
		margin-bottom: 30rpx;
	}
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
	}
	
	.subtitle {
		font-size: 26rpx;
		color: #666;
	}
	
	.application-list {
		margin-bottom: 100rpx;
	}
	
	.application-item {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
	}
	
	.application-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #eee;
	}
	
	.application-id {
		font-size: 28rpx;
		color: #666;
	}
	
	.application-status {
		font-size: 28rpx;
		font-weight: bold;
		padding: 6rpx 16rpx;
		border-radius: 6rpx;
	}
	
	.status-pending {
		color: #1890ff;
		background-color: #e6f7ff;
	}
	
	.status-initial-approved {
		color: #52c41a;
		background-color: #f6ffed;
	}
	
	.status-rejected {
		color: #f5222d;
		background-color: #fff1f0;
	}
	
	.status-contract-pending {
		color: #fa8c16;
		background-color: #fff7e6;
	}
	
	.status-approved {
		color: #52c41a;
		background-color: #f6ffed;
	}
	
	.status-cancelled {
		color: #999;
		background-color: #f5f5f5;
	}
	
	.application-content {
		margin-bottom: 30rpx;
	}
	
	.info-row {
		display: flex;
		margin-bottom: 15rpx;
	}
	
	.info-label {
		width: 200rpx;
		font-size: 28rpx;
		color: #666;
	}
	
	.info-value {
		flex: 1;
		font-size: 28rpx;
		color: #333;
	}
	
	.application-actions {
		display: flex;
		justify-content: flex-end;
	}
	
	.action-btn {
		margin-left: 20rpx;
		font-size: 26rpx;
		padding: 10rpx 20rpx;
		border-radius: 6rpx;
		background-color: #f5f5f5;
	}
	
	.primary-btn {
		background-color: #1890ff;
		color: #fff;
	}
	
	.cancel-btn {
		background-color: #f5f5f5;
		color: #ff4d4f;
	}
	
	.detail-btn {
		background-color: #f5f5f5;
		color: #666;
	}
	
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
	}
	
	.empty-icon {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
	}
	
	.empty-text {
		font-size: 32rpx;
		color: #333;
		margin-bottom: 10rpx;
	}
	
	.empty-desc {
		font-size: 26rpx;
		color: #999;
	}
	
	.bottom-action {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 20rpx 30rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.add-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #1890ff;
		color: #fff;
		font-size: 32rpx;
		padding: 20rpx 0;
		border-radius: 45rpx;
	}
	
	.btn-icon {
		margin-right: 10rpx;
	}
</style> 